<template>
  <div class="teaching-outline">
    <!-- 页面标题 -->
    <h1>教学大纲</h1>

    <!-- 一、课程基本信息 -->
    <section>
      <h2>一、课程基本信息</h2>
      <ul>
        <li>1、课程编号：{{ courseInfo.courseNumber }}</li>
        <li>2、课程英文名称：{{ courseInfo.courseEnglishName }}</li>
        <li>3、课程体系/类别：{{ courseInfo.courseType }}</li>
        <li>4、课程性质：{{ courseInfo.courseNature }}</li>
        <li>5、学时/学分：{{ courseInfo.courseHours }} 学时/{{ courseInfo.courseCredits }} 学分</li>
        <li>6、先修课程：{{ courseInfo.prerequisiteCourses }}</li>
        <li>7、适用专业：{{ courseInfo.applicableMajors }}</li>
        <li>8、使用教材：
          <ul>
            <li v-for="(textbook, index) in courseInfo.textbooks" :key="index">
              {{ textbook }}
            </li>
          </ul>
        </li>
      </ul>
    </section>

    <!-- 二、课程性质、课程目标及学生应达到的能力 -->
    <section>
      <h2>
        二、课程性质、课程目标及学生应达到的能力
        <el-button
          type="primary"
          @click="generateContent"
          class="generate-button"
        >
          智能生成
        </el-button>
      </h2>
      <div class="textarea-container">
        <!-- 使用 vue-up/vue-quill 编辑器显示和编辑生成的内容 -->
        <QuillEditor
          v-model:content="generatedContent"
          contentType="html"
          theme="snow"
          toolbar="full"
          class="content-textarea"
        />
        <!-- 显示加载提示，置于 textarea 内部 -->
        <div v-if="loadingContent" class="loading-indicator-inside">
          <el-spinner size="small"></el-spinner> 正在生成...
        </div>
      </div>
    </section>

    <!-- 三、课程教学重点和难点 -->
    <section>
      <h2>
        三、课程教学重点和难点
        <el-button
          type="primary"
          @click="generateFocusAndDifficulty"
          class="generate-button"
        >
          智能生成
        </el-button>
      </h2>
      <div class="textarea-container">
        <!-- 使用 vue-up/vue-quill 编辑器显示和编辑教学重点和难点 -->
        <QuillEditor
          v-model:content="generatedFocusAndDifficulty"
          contentType="html"
          theme="snow"
          toolbar="full"
          class="content-textarea"
        />
        <!-- 显示加载提示，置于 textarea 内部 -->
        <div v-if="loadingFocus" class="loading-indicator-inside">
          <el-spinner size="small"></el-spinner> 正在生成...
        </div>
      </div>
    </section>

    <!-- 四、教学内容 -->
    <section>
      <h2>
        四、教学内容
        <el-button
          type="primary"
          @click="generateTeachingContent"
          class="generate-button"
        >
          智能生成
        </el-button>
      </h2>
      <div class="textarea-container">
        <!-- 使用 vue-up/vue-quill 编辑器显示和编辑教学内容 -->
        <QuillEditor
          v-model:content="generatedTeachingContent"
          contentType="html"
          theme="snow"
          toolbar="full"
          class="content-textarea"
        />
        <!-- 显示加载提示，置于 textarea 内部 -->
        <div v-if="loadingTeachingContent" class="loading-indicator-inside">
          <el-spinner size="small"></el-spinner> 正在生成...
        </div>
      </div>
    </section>

    <!-- 新增的导出按钮 -->
    <el-button
      type="success"
      @click="exportToWord"
      class="export-button"
    >
      导出
    </el-button>
  </div>
</template>

<script>
import axios from "axios";
import JSZip from 'jszip';
import FileSaver from 'file-saver';
import PizZip from "pizzip";
import Docxtemplater from "docxtemplater";
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'

export default {
  name: "TeachingOutline",
  components: {
    QuillEditor
  },
  props: {
    courseName: {
      type: String,
      required: true,
    },
    courseNumber: {
      type: String,
      default: "未定义编号",
    },
  },
  data() {
    return {
      // 从后端获取的课程信息
      courseInfo: {
        courseNumber: "100075", // 示例值
        courseEnglishName: "Computer Networks Principles", // 示例值
        courseType: "专业核心课", // 示例值
        courseNature: "必修课", // 示例值
        courseHours: 48, // 示例值
        courseCredits: 3.0, // 示例值
        prerequisiteCourses: "程序设计C（A、B）、离散数学", // 示例值
        applicableMajors: "计算机科学与技术、信息安全、网络工程、网络空间安全", // 示例值
        textbooks: [
          "《通信原理》，樊昌信，电子工业出版社，2021年6月（第八版）",
        ], // 示例值
      },
      loadingContent: false, // 用于控制“课程性质、课程目标及学生应达到的能力”的加载状态
      loadingFocus: false, // 用于控制“课程教学重点和难点”的加载状态
      loadingTeachingContent: false, // 用于控制“教学内容”的加载状态
      // 智能生成的内容
      generatedContent: "",
      generatedFocusAndDifficulty: "",  // 新增变量，用于存储教学重点和难点的内容
      generatedTeachingContent: ""
    };
  },
  methods: {
    // 获取课程信息（模拟从数据库获取）
    async fetchCourseInfo() {
      try {
        const response = await axios.get("/api/course/info");
        this.courseInfo = response.data;
      } catch (error) {
        console.error("获取课程信息失败", error);
      }
    },
    // 调用后端接口智能生成内容
    async generateContent() {
      this.loadingContent = true;
      try {
        const response = await axios.post(
          "http://10.109.119.86:8080/v1/workflows/run", // 替换为实际的后端接口
          {
            inputs: {
              input: this.courseName, // 传递课程名称
            },
            response_mode: "blocking", // 固定参数
            user: "abc-123", // 固定参数，用户信息
          },
          {
            headers: {
              Authorization: "Bearer app-OLrK2c5UfYMJ2ginz3EgSLJE", // 替换为实际的 Bearer Token
            },
          }
        );
        if (response.data && response.data.data && response.data.data.outputs) {
          this.generatedContent = response.data.data.outputs.answer; // 显示返回的内容
        } else {
          this.$message.error("生成失败，请重试");
        }
      } catch (error) {
        console.error("智能生成内容失败", error);
        this.$message.error("生成失败，请稍后再试");
      } finally {
        this.loadingContent = false;
      }
    },

    // 新增方法：智能生成课程教学重点和难点
    async generateFocusAndDifficulty() {
      this.loadingFocus = true;
      try {
        const response = await axios.post(
          "http://10.109.119.86:8080/v1/workflows/run", // 替换为实际的后端接口
          {
            inputs: {
              input: this.courseName, // 传递课程名称
            },
            response_mode: "blocking", // 固定参数
            user: "abc-123", // 固定参数，用户信息
          },
          {
            headers: {
              Authorization: "Bearer app-hJWMTWrEorwFnwVtRdCMnZAm", // 替换为实际的 Bearer Token
            },
          }
        );
        if (response.data && response.data.data && response.data.data.outputs) {
          this.generatedFocusAndDifficulty = response.data.data.outputs.answer; // 显示返回的内容
        } else {
          this.$message.error("生成失败，请重试");
        }
      } catch (error) {
        console.error("智能生成教学重点和难点失败", error);
        this.$message.error("生成失败，请稍后再试");
      } finally {
        this.loadingFocus = false;
      }
    },

    // 新增方法：生成教学内容
    async generateTeachingContent() {
      this.loadingTeachingContent = true;
      try {
        const savedContent = localStorage.getItem("courseOutlineContent");
        const response = await axios.post(
          "http://10.109.119.86:8080/v1/workflows/run", // 替换为实际的后端接口
          {
            inputs: {
              //input: this.courseName, // 传递课程名称
              input: savedContent,

            },
            response_mode: "blocking", // 固定参数
            user: "abc-123", // 固定参数，用户信息
          },
          {
            headers: {
              Authorization: "Bearer app-3YNIsgpIHUHSmbgmP1VYeWNI", // 替换为实际的 Bearer Token
            },
          }
        );
        if (response.data && response.data.data && response.data.data.outputs) {
          this.generatedTeachingContent = response.data.data.outputs.answer; // 显示返回的内容
        } else {
          this.$message.error("生成失败，请重试");
        }
      } catch (error) {
        console.error("智能生成教学内容失败", error);
        this.$message.error("生成失败，请稍后再试");
      } finally {
        this.loadingTeachingContent = false;
      }
    },


    // 导出为Word文档
    exportToWord() {
      const templateUrl = "/templates/template.docx"; // 确保模板是 .docx 格式

      axios
        .get(templateUrl, { responseType: "arraybuffer" })
        .then((response) => {
          const content = response.data;
          try {
            const zip = new PizZip(content);

            // 确认文件结构是否有效
            const doc = new Docxtemplater(zip, {
              paragraphLoop: true,
              linebreaks: true,
            });

            // 设置动态内容
            doc.setData({
              courseNumber: this.courseInfo.courseNumber,
              courseEnglishName: this.courseInfo.courseEnglishName,
              courseType: this.courseInfo.courseType,
              courseNature: this.courseInfo.courseNature,
              courseHours: this.courseInfo.courseHours,
              courseCredits: this.courseInfo.courseCredits,
              prerequisiteCourses: this.courseInfo.prerequisiteCourses,
              applicableMajors: this.courseInfo.applicableMajors,
              textbooks: this.courseInfo.textbooks.join("\n"),
              generatedContent: this.generatedContent,
              generatedFocusAndDifficulty: this.generatedFocusAndDifficulty,
              generatedTeachingContent: this.generatedTeachingContent,
            });

            // 渲染文档
            doc.render();

            // 导出文档
            const out = doc.getZip().generate({ type: "blob" });
            FileSaver.saveAs(out, "teaching_outline.docx");
          } catch (error) {
            console.error("模板文件格式错误或损坏", error);
          }
        })
        .catch((error) => {
          console.error("加载模板失败", error);
        });
    },
  },
  mounted() {
    // 页面加载时获取课程信息
    this.fetchCourseInfo();
  },
};
</script>


<style scoped>
.teaching-outline {
  padding: 20px;
  font-family: Arial, sans-serif;
  background-color: #f9f9f9;
  border-radius: 8px;
}

h1 {
  font-size: 24px;
  margin-bottom: 20px;
}

h2 {
  font-size: 20px;
  margin-top: 20px;
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

li {
  margin: 5px 0;
  line-height: 1.6;
}

.generate-button {
  margin-left: 10px;
}

.textarea-container {
  position: relative;
}

.content-textarea {
  width: 100%;
  padding: 10px;
  font-size: 14px;
  margin-top: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
  resize: vertical;
}

.loading-indicator-inside {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  color: #888;
}

.export-button {
  margin-top: 10px;
  margin-left: 10px;
}
.content-textarea {
  height: 300px;
}
.quill-editor {
  min-height: 200px;
}
/* 添加一些样式以适应富文本编辑器 */
.content-textarea {
  height: 300px;
}
.quill-editor {
  min-height: 200px;
}

</style>
